import { useCallback, useRef, useState } from 'react'
import { chatAPI } from '../services/api'

export interface ChatMessage {
  role: 'system' | 'user' | 'assistant'
  content: string
  messageId?: string
  functionCall?: {
    name: string
    chineseName?: string
    arguments: any
  }
  functionResult?: {
    name: string
    chineseName?: string
    result: any
    message: string
  }
  functionError?: {
    name: string
    chineseName?: string
    error: string
  }
}

export interface TaskAction {
  type: 'create' | 'update' | 'view' | 'complete' | 'delete'
  taskId?: string
  label: string
  action: () => void
}

export function useEnhancedSSEChat(initialMessages: ChatMessage[] = []) {
  const [messages, setMessages] = useState<ChatMessage[]>(initialMessages)
  const [isStreaming, setIsStreaming] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [taskActions, setTaskActions] = useState<TaskAction[]>([])
  const abortRef = useRef<AbortController | null>(null)

  const send = useCallback(async (
    input: string,
    options?: { sessionId?: string; context?: any }
  ) => {
    setError(null)
    setTaskActions([])
    abortRef.current?.abort()
    const abort = new AbortController()
    abortRef.current = abort

    // 确保消息类型正确
    const userMessage: ChatMessage = { role: 'user', content: input }
    const nextMessages: ChatMessage[] = [...messages, userMessage]
    setMessages(nextMessages)
    setIsStreaming(true)

    try {
      // 创建符合API要求的消息数组
      // 使用messageId来跟踪当前消息，避免重复问题
      const messageId = Date.now().toString()
      
      const apiMessages = nextMessages.map(msg => ({
        role: msg.role,
        content: msg.content
      }))
      
      const stream = await chatAPI.streamEnhancedChat(apiMessages, { 
        ...options,
        messageId, // 传递messageId到后端
        signal: abort.signal 
      })
      const reader = stream.getReader()
      const decoder = new TextDecoder('utf-8')
      let assistantBuffer = ''
      
      // 添加新的assistant消息，使用messageId作为标识
      setMessages(prev => [...prev, { role: 'assistant', content: '', messageId }])

      const pushDelta = (delta: string) => {
        assistantBuffer += delta
        setMessages(prev => {
          const copy = [...prev]
          // 查找最后一条assistant消息，无论messageId是什么
          let found = false
          for (let i = copy.length - 1; i >= 0; i--) {
            if (copy[i].role === 'assistant') {
              copy[i] = { 
                ...copy[i], 
                content: assistantBuffer,
                // 保留原有messageId或使用当前messageId
                messageId: copy[i].messageId || messageId 
              }
              found = true
              break
            }
          }
          
          // 如果没有找到assistant消息，添加一个新的
          if (!found) {
            copy.push({ 
              role: 'assistant', 
              content: assistantBuffer, 
              messageId 
            })
          }
          
          return copy
        })
      }

      const handleFunctionResult = (result: any) => {
        setMessages(prev => {
          const copy = [...prev]
          // 查找最后一条assistant消息，无论messageId是什么
          let found = false
          for (let i = copy.length - 1; i >= 0; i--) {
            if (copy[i].role === 'assistant') {
              // 在清除 functionCall 之前保存工具名称
              const toolName = copy[i].functionCall?.chineseName || copy[i].functionCall?.name;
              copy[i] = { 
                ...copy[i], 
                functionResult: {
                  ...result,
                  chineseName: toolName || result.chineseName
                },
                // 清除 functionCall 状态，因为函数已经执行完成
                functionCall: undefined,
                // 保留原有messageId或使用当前messageId
                messageId: copy[i].messageId || messageId 
              }
              found = true
              break
            }
          }
          
          // 如果没有找到assistant消息，添加一个新的
          if (!found) {
            copy.push({ 
              role: 'assistant', 
              content: '', 
              functionResult: result,
              messageId 
            })
          }
          
          return copy
        })

        // 根据函数结果生成任务操作按钮
        generateTaskActions(result)
      }

      const handleFunctionError = (error: any) => {
        setMessages(prev => {
          const copy = [...prev]
          // 查找最后一条assistant消息，无论messageId是什么
          let found = false
          for (let i = copy.length - 1; i >= 0; i--) {
            if (copy[i].role === 'assistant') {
              // 在清除 functionCall 之前保存工具名称
              const toolName = copy[i].functionCall?.chineseName || copy[i].functionCall?.name;
              copy[i] = { 
                ...copy[i], 
                functionError: {
                  ...error,
                  chineseName: toolName || error.chineseName
                },
                // 清除 functionCall 状态，因为函数执行失败
                functionCall: undefined,
                // 保留原有messageId或使用当前messageId
                messageId: copy[i].messageId || messageId 
              }
              found = true
              break
            }
          }
          
          // 如果没有找到assistant消息，添加一个新的
          if (!found) {
            copy.push({ 
              role: 'assistant', 
              content: '', 
              functionError: error,
              messageId 
            })
          }
          
          return copy
        })
      }

      const generateTaskActions = (functionResult: any) => {
        const actions: TaskAction[] = []
        
        if (functionResult.name === 'create_task' && functionResult.result) {
          actions.push({
            type: 'view',
            taskId: functionResult.result.id,
            label: '查看任务',
            action: () => {
              // TODO: 导航到任务详情页面
              console.log('查看任务:', functionResult.result.id)
            }
          })
        }
        
        if (functionResult.name === 'query_tasks' && functionResult.result?.tasks) {
          functionResult.result.tasks.forEach((task: any) => {
            actions.push({
              type: 'view',
              taskId: task.id,
              label: `查看"${task.title}"`,
              action: () => {
                console.log('查看任务:', task.id)
              }
            })
          })
        }

        setTaskActions(actions)
      }

      while (true) {
        const { value, done } = await reader.read()
        if (done) break
        const chunk = decoder.decode(value, { stream: true })

        // 解析SSE: 逐行读取 data: ...
        const lines = chunk.split(/\n\n/)
        for (const block of lines) {
          const line = block.trim()
          if (!line) continue
          if (line.startsWith('data:')) {
            const payload = line.slice(5).trim()
            if (payload === '[DONE]') {
              setIsStreaming(false)
              return
            }
            try {
              const data = JSON.parse(payload)
              
                    // 不再检查消息ID是否匹配，因为前端和后端的messageId可能不同
      // 我们只需要确保消息被正确地添加到最新的assistant消息中
      if (data?.messageId && data?.messageId !== messageId) {
        console.log(`收到不同的消息ID: ${data.messageId} (后端) vs ${messageId} (前端)，但仍处理该消息`)
        // 不再跳过消息处理
      }
              
              // 处理各种消息类型
              if (data?.delta) {
                console.log('收到delta消息:', data.delta)
                pushDelta(data.delta)
              }
              if (data?.final) {
                console.log('收到final消息')
                setIsStreaming(false)
              }
              if (data?.functionResult) {
                console.log('收到functionResult消息:', data.functionResult)
                handleFunctionResult(data.functionResult)
              }
              if (data?.functionCall) {
                console.log('收到函数调用:', data.functionCall)
                // 更新消息中的函数调用信息
                setMessages(prev => {
                  const copy = [...prev]
                  // 查找最后一条assistant消息
                  let found = false
                  for (let i = copy.length - 1; i >= 0; i--) {
                    if (copy[i].role === 'assistant') {
                      copy[i] = { 
                        ...copy[i], 
                        functionCall: data.functionCall,
                        // 保留原有messageId或使用当前messageId
                        messageId: copy[i].messageId || messageId 
                      }
                      found = true
                      break
                    }
                  }
                  
                  // 如果没有找到assistant消息，添加一个新的
                  if (!found) {
                    copy.push({ 
                      role: 'assistant', 
                      content: '', 
                      functionCall: data.functionCall,
                      messageId 
                    })
                  }
                  
                  return copy
                })
              }
              if (data?.functionError) {
                console.log('收到functionError消息:', data.functionError)
                handleFunctionError(data.functionError)
              }
              if (data?.error) {
                console.log('收到error消息:', data.error)
                setError(data.message || data.error || 'STREAM_ERROR')
                setIsStreaming(false)
              }
            } catch (e) {
              // 非JSON数据或解析错误，记录并忽略
              console.warn('SSE解析错误:', e)
            }
          }
        }
      }
    } catch (e: any) {
      if (e?.name === 'AbortError') return
      setError(e?.message || 'STREAM_FAILED')
    } finally {
      setIsStreaming(false)
    }
  }, [messages])

  const cancel = useCallback(() => {
    abortRef.current?.abort()
    setIsStreaming(false)
  }, [])

  const clearMessages = useCallback(() => {
    setMessages(initialMessages)
    setTaskActions([])
    setError(null)
  }, [initialMessages])

  return { 
    messages, 
    setMessages, 
    isStreaming, 
    error, 
    taskActions,
    send, 
    cancel, 
    clearMessages 
  }
}
